<template>
  <div class="app-container">
    <el-tabs v-model="activeName" class="elTabs">
      <el-tab-pane label="图片" name="photo">
        <div>
          <div class="leftBar">
            <el-row class="tac">
              <el-col :span="12">
                <el-menu
                  default-active="2"
                  class="el-menu-vertical-demo"
                  active-text-color="red"
                >
                  <el-menu-item :index="JSON.stringify(2)" @click="selectAll">
                    <span slot="title">全部</span>
                  </el-menu-item>
                  <el-menu-item v-for="item in baseClassifyList" :key="item" class="item" :index="item" @click="typeChange(item)">
                    <span slot="title">{{ item }}</span>
                  </el-menu-item>
                </el-menu>
              </el-col>
            </el-row>
          </div>
          <div class="picInfo">
            <el-row class="centers">
              <div class="choose">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">当页全选 | 已选{{ bottomCheckboxFlagCount }}项 | 批量操作</el-checkbox>
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showBatchChange">修改分组</el-button>&nbsp;&nbsp;
                <el-popconfirm
                  title="确认删除所选全部吗？"
                  confirm-button-type="warning"
                  confirm-button-text="确定"
                  class="customConfirm"
                  @onConfirm="batchRemove"
                >
                  <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" @click="selectJudge">删除</el-button>
                </el-popconfirm>
                &nbsp;<el-button type="primary" size="mini" icon="el-icon-edit" @click="showAdd">新增</el-button>
                <div class="search">
                  <el-input v-model="searchForm.fileName" class="search-input" size="small" placeholder="请输入图片名称" :clearable="true" />
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="searchGetList">搜索</el-button>
                </div>
              </div>
              <div class="formData">
                <el-col v-for="item in tableData.list" :key="item.id" :span="4" :offset="1" align="left">
                  <div id="cards" class="choose-image-list">
                    <div class="choose-image-item stys">
                      <img v-if="item.extensionName && item.extensionName === 'svg'" class="choose-image imas" :src="cfg.imageDomain + item.path" alt="" border="0">
                      <svga v-if="item.extensionName && item.extensionName === 'svga'" :src="cfg.imageDomain + item.path" style="height:170px;width:170px" :options="svgaOptions" class="choose-image" />
                      <img v-else class="choose-image imas" :src="cfg.imageDomain + item.path + '?imageView2/2/w/300'" alt="" border="0">
                    </div>
                  </div>
                  <div class="fileStys" :title="item.fileName+'.'+item.extensionName">
                    <el-checkbox v-model="item.result" class="checkbox" @change="handleCheckedCitiesChange(item)" />
                    {{ item.fileName }}.{{ item.extensionName }}</div>
                  <div class="pads">
                    <el-button type="text" @click="showUpdate(item)">编辑
                    </el-button>
                    <el-button type="text">
                      <el-link v-clipboard:copy="cfg.imageDomain + item.path" v-clipboard:success="clipboardSuccess" type="primary">
                        链接
                      </el-link>
                    </el-button>
                    <el-popconfirm
                      title="确认删除吗？"
                      confirm-button-type="warning"
                      confirm-button-text="确定"
                      class="customConfirm"
                      @onConfirm="remove(item)"
                    >
                      <el-button slot="reference" type="text">删除</el-button>
                    </el-popconfirm>
                  </div>
                </el-col>
              </div>
            </el-row>
            <el-pagination v-if="tableData.total > 0" class="pagination" :page-count="tableData.pageCount" :current-page.sync="tableData.pageNo" :limit.sync="tableData.pageSize" @current-change="pageChange" />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="视频" name="video">
        <res-video-list />
      </el-tab-pane>
    </el-tabs>
    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="编辑" :visible.sync="updateDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">

        <el-form-item label="名称" prop="toolUrl">
          <el-input v-model="formData.props.fileName" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="图片分类" prop="classificationId">
          <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true">
            <el-option
              v-for="item in baseClassifyList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
          <el-button type="text" @click="refresh">刷新</el-button>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="批量修改" :visible.sync="batchChangeDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">

        <el-form-item label="图片分类">
          <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true" transfer="true" :popper-append-to-body="false">
            <el-option
              v-for="item in baseClassifyList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
          <el-button type="text" @click="refresh">刷新</el-button>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchChangeDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="batchChangeType">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="新增" :visible.sync="formData.formDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">
        <el-form-item label="上传图片">
          <el-upload
            class="upload-demo"
            accept="image/jpeg,image/gif,image/png,image/jpg,.svg,.svga"
            :action="cfg.apiDomain + '/file/upload/upload?uploadItem=resPhotoLib'"
            name="file"
            multiple
            :limit="10"
            :show-file-list="false"
            :on-exceed="exceedLimit"
            :on-success="imageUploadSuccess"
            :before-upload="imageUploadBefore"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <div v-for="image in imagesList" :key="image.path">
          <el-form-item v-if="imagesList.length > 1">
            <img
              style="width: 370px; height: 250px; cursor:pointer"
              :src="cfg.imageDomain + image.path"
            >
          </el-form-item>
          <el-form-item v-if="imagesList.length === 1 && image.extensionName !== 'gif' && image.extensionName !== 'png' && image.extensionName !== 'svg' && image.extensionName !== 'svga' ">
            <div style="height: 300px;">
              <wj-cropper
                ref="cropper"
                :img="cfg.imageDomain + image.path"
              />
            </div>
          </el-form-item>
          <el-form-item v-if="imagesList.length === 1 && (image.extensionName == 'gif' || image.extensionName == 'png' || image.extensionName == 'svg' || image.extensionName == 'svga') ">
            <img
              v-if="image.path.indexOf('.svga') === -1"
              style="width: 370px; height: 250px; cursor:pointer"
              :src="cfg.imageDomain + image.path"
            >
            <svga :src="cfg.imageDomain + image.path" :options="svgaOptions" style="height: 150px;width:150px" class="choose-image" />
          </el-form-item>
          <el-form-item label="图片分类" prop="classificationId">
            <el-select v-model="formData.props.classificationId" placeholder="请选择分类" :clearable="true">
              <el-option
                v-for="item in baseClassifyList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-button type="text" @click="addClassificationDialog = true">添加分组</el-button>
            <el-button type="text" @click="refresh">刷新</el-button>
          </el-form-item>
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="image.fileName" placeholder="请输入文件名" />
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formData.formDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- todo 调整表单字段 -->
    <el-dialog :close-on-click-modal="false" title="新增分类" :visible.sync="addClassificationDialog">
      <el-form ref="formData" :model="formData.props" :rules="formData.rules" label-width="180px">
        <el-form-item label="分类名称">
          <el-input v-model="formData.props.classificationId" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassificationDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="saveClassification">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-loading="loading"
      :close-on-click-modal="false"
      class="upload-img-dialog"
      element-loading-text="拼命上传中"
      :visible.sync="uploadProgressDialogVisible"
    />
  </div>
</template>

<script>
import WjCropper from '@/components/wejoy/WjCropper'
import request from '@/utils/request'
import clipboard from '@/directive/clipboard/index.js'
import resVideoList from '@/views/video-middle-station/res/resVideoLibList.vue'

export default {
  name: 'ResPhotoLibList',
  components: { WjCropper, resVideoList },
  directives: { clipboard },
  data() {
    return {
      props: {
        autoCropWidth: '',
        autoCropHeight: '',
        //  是否开启截图框宽高固定比例
        fixed: false,
        // 固定截图框大小 不允许改变
        fixedBox: false
      },
      activeName: 'photo',
      extensionNameCondition: '',
      fileNameCondition: '',
      bottomCheckboxFlagCount: 0,
      baseClassifyCondition: '',
      batchIdList: [],
      prepareIdList: [],
      chooseImageDialog: false,
      btnSubmitDisabled: false,
      updateDialog: false,
      addClassificationDialog: false,
      batchChangeDialog: false,
      checkAll: false,
      isIndeterminate: false,
      uploadProgressDialogVisible: false,
      loading: false,
      baseClassifyList: '',
      searchForm: {
        fileName: '',
        classificationId: ''
      },
      imagesList: [],
      tableVideoData: {
        pageNo: 1,
        pageSize: 12,
        total: 0,
        pageCount: 0,
        list: []
      },
      tableData: {
        pageNo: 1,
        pageSize: 12,
        total: 0,
        pageCount: 0,
        list: []
      },
      formData: {
        formDialog: false,
        // 表单字段, 请自行删除不需要的
        props: {
          extensionName: '',
          path: '',
          uploaderType: '',
          imgHeight: '',
          imgWidth: '',
          createUserId: '',
          fileSize: '',
          dataStatus: '',
          fileName: '',
          classificationId: ''
        },
        // 表单校验规则, 默认增加了必填, 请自行限制长度或者其他修改
        rules: {
          extensionName: this.formRules({ required: true }),
          path: this.formRules({ required: true }),
          uploaderType: this.formRules({ required: true }),
          imgHeight: this.formRules({ required: true }),
          imgWidth: this.formRules({ required: true }),
          createUserId: this.formRules({ required: true }),
          fileSize: this.formRules({ required: true }),
          dataStatus: this.formRules({ required: true }),
          fileName: this.formRules({ required: true }),
          classificationId: this.formRules({ required: true })
        }
      },
      svgaOptions: {
        loop: 0,
        fillMode: 'forwards',
        playMode: 'forwards',
        startFrame: 0,
        endFrame: 0,
        autoPlay: true
      }
    }
  },

  mounted: function() {
    this.getList({
      pageNo: 1,
      pageSize: this.tableData.pageSize
    })
    this.registerFilter('EnumStatus');
    this.getBaseClassify();
  },
  methods: {
    imageUploadSuccess: function(response, file, fileList) {
      if (this.formData.props.path) {
        this.imagesList = []
      }
      if (this.imagesList.length === 1 && this.imagesList[0].extensionName === 'svga') {
        this.imagesList = []
      }
      const result = response.data;
      this.formData.props.fileName = file.name.split('.')[0]
      this.imagesList.push({
        id: this.formData.props.id,
        fileName: file.name.split('.')[0],
        path: result.key,
        fileSize: result.fileSize,
        extensionName: result.suffix,
        imgHeight: result.height,
        imgWidth: result.width,
        type: '1' // 默认选中第一个类型
      });
      this.uploadProgressDialogVisible = false;
      this.loading = false;
    },
    imageUploadBefore: function(file) {
      this.loading = true;
      this.uploadProgressDialogVisible = true;
    },
    refresh() {
      this.getBaseClassify();
      this.$message.success('刷新成功');
    },
    exceedLimit: function(files, fileList) {
      this.$message.warning('超出图片上传上限(10)')
    },
    clipboardSuccess() {
      this.$message({
        message: '复制链接成功',
        type: 'success'
      })
    },
    pageChange: function(pageNo) {
      this.tableData.pageNo = pageNo;
      this.getList({
        pageNo: pageNo,
        pageSize: this.tableData.pageSize
      })
    },
    saveClassification() {
      var _this = this;
      this.baseClassifyList.push(this.formData.props.classificationId);
      const classification = this.baseClassifyList.join(',');
      if (this.formData.props.classificationId.length === 0) {
        _this.$message.error('请填写分组信息！');
        return
      }
      request({
        url: '/system/sysBaseParam/setValueByUnicode',
        method: 'post',
        data: {
          uniCode: 'PHOTO_CLASSIFICATION',
          value: classification
        }
      }).then(res => {
        _this.addClassificationDialog = false;
        _this.formData.props.classificationId = '';
        _this.$message.success('操作成功');
        _this.getBaseClassify({
        });
      })
    },
    changeTypeClassification(image, item) {
      image.classificationId = item;
    },
    getList: function(req) {
      var _this = this;
      req.fileName = this.fileNameCondition;
      req.extensionName = this.extensionNameCondition;
      req.classificationId = this.baseClassifyCondition;
      request({
        url: '/res/photoResLib/getPageList',
        method: 'post',
        data: {
          pageNo: req.pageNo || this.tableData.pageNo,
          pageSize: req.pageSize || this.tableData.pageSize,
          ...this.searchForm
        }
      }).then(res => {
        const data = res.data;
        _this.tableData.total = data.total;
        _this.tableData.list = data.rows;
        _this.tableData.pageCount = data.pageCount;
        _this.tableData.pageNo = req.pageNo;
        this.prepareIdList = [];
        this.batchIdList = [];
        this.imagesList = [];
        this.isIndeterminate = false;
        this.checkAll = false;
        this.bottomCheckboxFlagCount = 0;
        for (let i = 0; i < res.data.rows.length; i++) {
          _this.tableData.list.result = false;
          this.prepareIdList.push(data.rows[i].id)
        }
      })
    },
    handleCheckAllChange(val) {
      if (val) {
        this.batchIdList = this.prepareIdList;
        this.tableData.list.forEach(item => {
          item.result = true;
        })
        this.bottomCheckboxFlagCount = this.batchIdList.length;
      } else {
        this.batchIdList = [];
        this.tableData.list.forEach(item => {
          item.result = false;
        })
        this.bottomCheckboxFlagCount = 0;
      }
    },
    handleCheckedCitiesChange(item) {
      if (item.result === true) {
        this.batchIdList.push(item.id);
        this.bottomCheckboxFlagCount++;
        if (this.tableData.list.length !== this.batchIdList.length) {
          this.isIndeterminate = true;
          this.checkAll = false;
        } else {
          this.isIndeterminate = false;
          this.checkAll = true;
        }
      } else if (item.result === false) {
        this.batchIdList.splice(this.batchIdList.indexOf(item.id), 1)
        this.bottomCheckboxFlagCount--;
        if (this.checkAll) {
          this.checkAll = false;
          this.isIndeterminate = true;
        } else if (this.batchIdList.length === 0) {
          this.isIndeterminate = false;
          this.checkAll = false;
        }
      }
    },
    getBaseClassify: function() {
      var _this = this;
      request({
        url: '/system/sysBaseParam/selectValueByUnicode?unicode=PHOTO_CLASSIFICATION',
        method: 'post'
      }).then(res => {
        _this.baseClassifyList = res.data.split(',');
      })
    },
    searchGetList: function() {
      this.getList({
        pageNo: 1,
        pageSize: this.tableData.pageSize
      })
    },
    showAdd: function() {
      this.formData.props = {
        id: '',
        extensionName: '',
        path: '',
        uploaderType: '',
        imgHeight: '',
        imgWidth: '',
        createUserId: '',
        fileSize: '',
        dataStatus: '',
        fileName: '',
        classificationId: '',
        status: '1'
      }
      this.imagesList = [];
      this.formData.formDialog = true;
    },
    showUpdate: function(data) {
      this.imagesList = [];
      this.formData.props = {
        id: data.id,
        extensionName: data.extensionName,
        path: data.path,
        uploaderType: data.uploaderType,
        imgHeight: data.imgHeight,
        imgWidth: data.imgWidth,
        createUserId: data.createUserId,
        fileSize: data.fileSize,
        dataStatus: data.dataStatus,
        fileName: data.fileName,
        classificationId: data.classificationId
      };
      this.imagesList.push(this.formData.props);
      this.updateDialog = true;
    },
    typeChange(item) {
      this.searchForm.classificationId = item;
      this.getList({ pageNo: 1 });
    },
    selectAll() {
      this.searchForm.classificationId = '';
      this.getList({ pageNo: 1 });
    },
    showBatchChange() {
      if (this.batchIdList.length === 0) {
        this.$message.error('请勾选文件');
        return;
      }
      this.batchChangeDialog = true;
    },
    batchChangeType() {
      this.batchIdList.forEach(id => {
        const props = {
          id: id,
          classificationId: this.formData.props.classificationId
        };
        this.imagesList.push(props);
      })
      this.save();
    },
    save: function() {
      var _this = this;
      this.disableBtn(this, 'btnSubmitDisabled');
      this.$refs.formData.validate(function(valid) {
        if (!valid) {
          return;
        }
        var images = _this.imagesList;
        console.log(_this.imagesList);
        if (images == null || images === '') {
          this.$message.warning('图片不能为空');
          return;
        }
        if (images.id === '' && images.length === 1 && images[0].extensionName !== '.gif' && images[0].extensionName !== 'png' && images[0].extensionName !== 'svg' && images[0].extensionName !== 'svga') {
          _this.$refs.cropper[0].cropUpload(function(file) {
            var imagesList = [];
            var image = {};
            image.path = file.key;
            image.fileSize = file.fileSize;
            image.extensionName = file.suffix;
            image.imgHeight = file.height;
            image.imgWidth = file.width;
            image.fileName = images[0].fileName;
            image.classificationId = images[0].classificationId
            image.id = images[0].id
            imagesList.push(image)
            request({
              url: '/res/photoResLib/saveList',
              method: 'post',
              data: {
                photoReslibMap: imagesList
              }
            }).then(res => {
              _this.formData.formDialog = false;
              _this.updateDialog = false;
              _this.batchChangeDialog = false;
              _this.getList({
                pageNo: 1,
                pageSize: _this.tableData.pageSize
              })
              _this.$message.success('保存成功');
            })
          })
        } else {
          images.forEach(item => {
            item.classificationId = _this.formData.props.classificationId;
          })
          request({
            url: '/res/photoResLib/saveList',
            method: 'post',
            data: {
              photoReslibMap: images
            }
          }).then(res => {
            _this.formData.formDialog = false;
            _this.updateDialog = false;
            _this.batchChangeDialog = false;
            _this.getList({
              pageNo: 1,
              pageSize: _this.tableData.pageSize
            })
            _this.$message.success('保存成功');
          })
        }
      })
    },
    batchRemove() {
      if (this.batchIdList.length === 0) {
        this.$message.error('请勾选文件');
        return;
      }
      this.batchIdList.forEach(id => {
        const props = {
          id: id,
          status: -9
        };
        this.imagesList.push(props);
      })
      this.save();
    },
    selectJudge: function() {
      if (this.batchIdList.length === 0) {
        this.$message.error('请勾选文件');
        return;
      }
    },
    remove: function(data) {
      var _this = this;
      request({
        url: '/res/photoResLib/delete?id=' + data.id,
        method: 'post',
        data: {}
      }).then(res => {
        _this.$message.success('删除成功');
        _this.getList({
          pageNo: 1,
          pageSize: _this.tableData.pageSize
        })
      })
    }
  }
}
</script>

<style>
  .choose {
    margin-left: 30px;
    text-align: left;
    width: 100%;
  }
  .leftBar {
    width: 40px;
    float: left;
  }
  .elTabs {
    width: 100%;
    float: left;
  }
  .formData {
    margin-top: 40px;
  }
  .picInfo {
    float: left;
    width: 91%;
  }
  #cards {
    background: #f2f2f2;
    margin-top: 30px;
    padding: 0px;
    height:205px;
  }
  .tac {
    float: left;
    width: 250px;
  }
  .stys{
    height:100%;
    width: 100%;
  }
  .pagination {
    margin-left: 140px;
  }
  .centers {
    text-align: center;
    left: 6%;
  }
  .fileStys {
    display:block;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    font-weight: 400;
    font-style: normal;
    font-size: 14px;
    text-align: left;
    margin-top: 10px;
  }
  .stys img {
    border: 1px solid #f2f2f2;
    height:106%;
    width: 105%;
    margin-top: -2.2%;
    margin-left: -2.5%;
  }
  .imas{
    object-fit:scale-down;
  }
  .pads {
    padding-top: 5px;
    display:flex;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    justify-content:space-between;
  }
  .search{
    float: right;
    margin-right: 265px;
  }
</style>

